package com.bosssoft.trainee.nontax.controller;

import cn.hutool.core.date.DateUtil;
import com.bosssoft.trainee.nontax.common.Result;
import com.bosssoft.trainee.nontax.entity.po.Message;
import com.bosssoft.trainee.nontax.entity.po.User;
import com.bosssoft.trainee.nontax.service.IMessageService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/message")
public class MessageController extends BaseController{

    @Resource
    private IMessageService messageService;

    @PostMapping
    public Result<?> save(@RequestBody Message message) {
        User user = (User) getUser().getData();
        message.setUsername(user.getUsername());
        message.setTime(DateUtil.formatDateTime(new Date()));
        return Result.success(messageService.save(message));

    }

    @PutMapping
    public Result<?> update(@RequestBody Message message) {
        return Result.success(messageService.updateById(message));
    }

    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id) {
        messageService.removeById(id);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result<?> findById(@PathVariable Long id) {
        return Result.success(messageService.getById(id));
    }

    @GetMapping
    public Result<?> findAll() {
        return Result.success(messageService.list());
    }

    // 查询所有数据
    @GetMapping("/foreign/{id}")
    public Result<?> foreign(@PathVariable Integer id) {
        return Result.success(findByForeign(id));
    }

    @GetMapping("/page")
    public Result<?> findPage(@RequestParam(required = false, defaultValue = "") String name,
                                                @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                                                @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        return messageService.findPage(name, pageNum, pageSize);
    }

    @GetMapping("/getByWords")
    public Result<?> getByWords(@RequestParam(required = false, defaultValue = "1") Integer pageNum,
                                @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        return messageService.getByWords(pageNum, pageSize);
    }

    private List<Message> findByForeign(Integer foreignId) {
        return messageService.findByForeign(foreignId);
    }

}
